import axios from '@/utils/request';

// 获取错误码翻译表
const getErrorCode = (data) => {
    return axios.get('/iot_user/code', {
        params: data
    })
}

// 获取注册协议和隐私政策   type=1 为注册协议，type=2 为隐私政策
const getRichText = (data) => {
    return axios.get('/iot_login/user/getAgreement', {
        params: data
    })
}

// 获取短信验证码
const getSms = (data) => {
    return axios.get('/iot_login/user/getSmsCode', {
        params: data
    })
}

// 密码重置
const toResetPassword = (data) => {
    return axios.post('/iot_login/user/forgetPass', data)
}

// 注册
const toRegister = (data) => {
    return axios.post('/iot_login/user/register', data)
}

// 密码登录
const toLogin = (data) => {
    return axios.post('/iot_login/user/login', data)
}

// 短信验证码登录
const toLoginSms = (data) => {
    return axios.post('/iot_login/user/verificationLogin', data)
}

// 腾讯防水墙后台验证
const toVerifyGraph = (data) => {
    return axios.post('/iot_login/user/verifyGraph', data)
}

// 登录成功后处理返回信息
const loginSuccess = function(data) {
    console.info("login successfull", data)

    if (data) {
        let href = '';
        localStorage.setItem('token', data.token);

        let origin = window.location.origin;
        let redirect = getUrlParam('redirect');

        if (redirect) {
            // 从其它应用进入的登录页
            let hash = getUrlParam('hash');
            href = `${origin}${redirect}`
            if (hash) {
                href = `${href}#/${hash}`
            }
        } else {
            // 直接打开的登录页
            if (process.env.NODE_ENV === 'production') {
                href = `${origin}/myApp/`
            } else {
                href = `${origin}/myApp/`
            }
        }

        window.location.href = href;
    }
}

// 获取地址栏参数
const getUrlParam = (name) => {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    let r = window.location.search.substr(1).match(reg);
    if (r !== null) return decodeURIComponent(r[2]);
    return null;
}

export {
    getErrorCode,
    getRichText,
    getSms,
    toResetPassword,
    toRegister,
    toLogin,
    toLoginSms,
    toVerifyGraph,
    loginSuccess,
    getUrlParam
}